package imageViewer;

import imagesBuffer.ArrayBitmapBuffer;
import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.MotionEvent;
import android.widget.ImageView;

public class ImageListener implements ImageReloader{
	private ArrayBitmapBuffer buffer;
	private ImageView currentImage;
	private int screenWidth;
	
	public ImageListener(String[] paths,int initialPosition,
			ImageView currentImage,ImageView otherImage,
			int screenWidth,Activity caller,int screenHeight) {
		this.currentImage=currentImage;
		this.screenWidth=screenWidth;
		buffer=new ArrayBitmapBuffer(paths, initialPosition, this);
	}
	
	/**
	 * cambia l'immagine corrente a seconda della posizione del puntatore
	 */
	public void manageTouch(MotionEvent event){
		currentImage.getLayoutParams();
		if(event.getAction()==MotionEvent.ACTION_DOWN){
			if(event.getX()>screenWidth/2){
				buffer.next();
			}else{
				buffer.prev();
			}
			reloadImages();
		}
	}
	
	/**
	 * richiama il thread principale per aggiornare l'immagine visualizzata
	 */
	@Override
	public synchronized void reloadImages() {
		Handler refresher=new Handler(Looper.getMainLooper());
		refresher.post(new Runnable() {
			@Override
			public void run() {
				try {
					currentImage.setImageBitmap(buffer.getCurrentImage());
				} catch (Exception e) {
					
				}
			}
		});
	}
}
